<?php

require_once('../functions/mainFns.php');
session_start();

//var_dump($_REQUEST);
	$act 		= $_REQUEST['act'];
	$username 	= @$_REQUEST['username'];
	$password 	= @$_REQUEST['password'];
	$nickname 	= @$_REQUEST['nickname'];
	$userid 	= @$_REQUEST['userid'];
	$imgsrc 	= @$_REQUEST['imgsrc'];

//注册动作
if($act == 'register'){
	$ds 	= Dataservice::getInstance();
	$res 	= $ds->register($username,$password,$nickname);
	$res	= json_decode($res);
	$status = $res[0]->status;
	echo $status;
}	

//用户的detail
if($act == 'getuserdetail'){
	echo json_encode(getuserdetail($userid));
	
}

//登录动作
if($act == 'login'){
	$ds 	= Dataservice::getInstance();
	$res 	= $ds->login($username,$password);
	$res	= json_decode($res);
	$status =  $res[0]->status;
	$userid = @$res[1]->info->id;
	if($status == 'fail'){
		echo 'fail';
	}else if($status == 'success'){
		$_SESSION['userid']	= $userid;
		echo 'success';
	}
}

//查看注册姓名是否被用
if($act == 'checkreg'){
	$ds 	= Dataservice::getInstance();
	$res 	= $ds->checkreg($username);
	$res	= json_decode($res);
	$status = $res[0]->status;
	echo $status;
}

//用户是否登录
if($act == 'checkloged'){
	$log = @$_SESSION['userid'];
	echo $log;
}

//用户退出登录
if($act == 'logout'){
	session_unset();
	session_destroy();
	echo 1;
}

//上传头像
if($act == 'uploadhead'){
	$userid = $_SESSION['userid'];
	//先将base64-url编码存到本地images/tmp路径下
	$imgsrc = explode('base64,',$imgsrc);
	$base64_img = $imgsrc[1];
	$tmp = base64_decode($base64_img);//解码到临时文件
	$path = "../images/tmp/";
	file_put_contents($path."$userid.jpg", $tmp);
 	$nowpath = $path.$userid.".jpg";
	$imgname = $userid.'.jpg';
	unset($imgsrc);
	unset($base64_img);
	unset($tmp);
	//读取本地图片信息，进行尺寸判断
	$imginfo = getimagesize($nowpath);
	if($imginfo[0] > 100){	
		//得到裁剪图片比例
		$per = 100/$imginfo[0];	
		list($width, $height) = getimagesize($nowpath);
		$n_w=$width*$per;
		$n_h=$height*$per;
		$new=imagecreatetruecolor($n_w, $n_h);
		//根据图片格式，拷贝部分图像并调整
		$imgtype = $imginfo[2];		
		switch($imgtype){
			case 1:
				$img=imagecreatefromgif($nowpath);
				break;		
			case 2:
				$img=imagecreatefromjpeg($nowpath);
				break;		
			case 3:
				$img=imagecreatefrompng($nowpath);
				break;		
			case 4:
				$img=imagecreatefromwbmp($nowpath);
				break;	
			default:
				$img=imagecreatefromjpeg($nowpath);
		}
		imagecopyresized($new, $img,0, 0,0, 0,$n_w, $n_h, $width, $height);
		imagejpeg($new,$path.$userid.'new.jpg');//图像输出新图片、另存为
		imagedestroy($new);
		imagedestroy($img);
		$imgname = $userid."new.jpg";
	}
	//传输裁剪后或者最终图像  注意！CURL传输文件的时候必须用绝对路径！并且前面加@
 	$nowpath = dirname(__FILE__)."/../images/tmp/".$imgname;
	$ds  = Dataservice::getInstance();
	$res = $ds->uploadhead($userid,$nowpath);
 	$res = json_decode($res);
	$status  =  $res[0]	-> status;
	$id  	 = @$res[1]	-> info->id; 
 	if($status == 'fail'){
		echo '0';
	}else if($status == 'success'){
		echo DATAWEB."images/head/$userid.jpg";
	}     
}


?>